-- RewardAmzingBoxPanel

local RewardAmazingBoxRender = import(".renders.RewardAmazingBoxRender")
local ResRender = require("app.widget.renders.ResRender")
local RewardAmazingBoxTipsView = import(".RewardAmazingBoxTipsView")

local ClassRef = app.mvc.createPanelClass(...)

function ClassRef.create(node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.AmazingBoxPanel))
    sprite:init()
    return sprite
end

function ClassRef:init(data)
    self.super.init(self, data)
    self:setContentSize(self._ui.Panel:getContentSize())
    self._model = app:getInst("RewardModel")
    self._icon = self._ui.icon
    self._tlt = self._ui.tlt
    self._tltBg = self._ui.bg02
    self._Text = self._ui.Text_1
    self._panelDate = self._ui.Panel_date --内容面板
    self._Text2 = self._ui.Text_2
    self._Text2:setVisible(false)

    self._allRender = {}

    for i = 1, 4 do
        local render = RewardAmazingBoxRender.create(self._ui["Panel/Panel_date/node_"..i])
        table.insert(self._allRender, render)
        local boxNode = render:findChild("Panel/icon_1")
        boxNode:setTouchEnabled(true)
        boxNode:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                self:showTips(i)
            end
        end)
        local boxNode2 = render:findChild("Panel/icon_rinu")
        boxNode2:setTouchEnabled(true)
        boxNode2:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                self:showTips(i)
            end
        end)
        render:setVisible(false)
        render:getTimeline():gotoFrameAndPause(0)
    end

    self._resRender = ResRender.create(self._ui.Panel_gold)
    self._resRender:setVisible(false)

    self:refresh()
end

function ClassRef:refresh()
    if self._data then
        self:setVisible( true )

        local data = self._data
        self._icon:loadTexture(Res.activityIconPath..data.iconName..".png")
        self._tlt:setString(L(data.name))
        self._Text:setString(L(data.des))

        if not data.packageInfos then return end

        self._cost = data.packageInfos[1].cost
        self._conf = GD:getActivityAmazingAwardById(data.packageInfos[1].packageID)
        self:updateMoney()
        for k, v in ipairs(data.packageInfos) do
            if k <= #self._allRender then
                self._allRender[k]:setData(v)
                self._allRender[k]:onOperate(self._onOperate)
                self._allRender[k]:setVisible(true)
            end
        end
        self:refreshTime()
    else
        self:setVisible(false)
    end
end

function ClassRef:refreshTime()
    if not self._data then return end
    if self._delayAct then
		self:stopAction(self._delayAct)
		self._delayAct = nil
	end
    local endTimes = self._data.endTime
    local serverTime = app.session:getServerTime() or os.time()
    if endTimes - serverTime  <= 0 then
        self._Text2:setVisible(false)
        return
    else
        local param = TimeUtil.secondsToStr((endTimes - serverTime), 4)    
        self._Text2:setVisible(true)
        if param[1] then
            self._Text2:setString(table.concat({L("activitydes_6001_2"), string.format(L("countdowen_day"), param[1])}))
        elseif param[2] then
            self._Text2:setString(table.concat({L("activitydes_6001_2"), string.format(L("countdowen_hour"), param[2])}))
        elseif param[3] then
            self._Text2:setString(table.concat({L("activitydes_6001_2"), string.format(L("countdowen_min"), param[3])}))
        end
        local delayTime = 1 -- 延时多长时间刷新
        if param[1] then
            if param[2] then
                delayTime = param[2]*3600
            elseif param[3] then
                delayTime = param[3]*60
            end
        elseif param[2] then
            delayTime = param[3]*60
        elseif param[3] then
            delayTime = 60
            if param[3] <= 1 then
                delayTime = 1
            end
        end
        self._delayAct = self:performWithDelay(function()
            self._delayAct = nil
            self:refreshTime()
        end, delayTime)
    end
end

function ClassRef:updateMoney()
    if self._resRender then
        local param = self._model:parseMoneyInfo()
        if param then
            self._resRender:setVisible(true)
            self._resRender:setData(param)
            if self._conf then
                local iconPath = string.format("%s%s.png",Res.itemPath,self._conf.coinIcon)
                self._resRender:setIcon(iconPath)
            end
        end
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

function ClassRef:showTips(i)
    local render = self._allRender[i]
    if render then
        local data = render:getData()
        if self._amazingBoxTips then
            self._amazingBoxTips:setData(data)
        else
            self._amazingBoxTips = RewardAmazingBoxTipsView.create()
            self._amazingBoxTips:setData(data)
            self._ui["Panel"]:addChild(self._amazingBoxTips)

            -- 点击空白区域关闭
            display.nodeRemoveForNotHit(self._amazingBoxTips, function()
                if self._amazingBoxTips then
                    self._amazingBoxTips:removeFromParent()
                    self._amazingBoxTips = nil
                end
            end)
        end
        local triggerNodeBoundingBox = render:getBoundingBox()
        local worldPosTemp = render:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
        triggerNodeBoundingBox.x = worldPosTemp.x
        triggerNodeBoundingBox.y = worldPosTemp.y
        display.adjustNodePos( triggerNodeBoundingBox, self._amazingBoxTips )      
    end
end

function ClassRef:refreshAmazingAwardPanel(param, type)
    if not param or not type then return end
    local packageId = param.packageID
    for i = 1, #self._allRender do
        local render = self._allRender[i]
        local data = render:getData()
        if packageId == data.packageID then
            local timeline = render:getTimeline()
            if timeline then
                timeline:clearLastFrameCallFunc()
                timeline:gotoFrameAndPlay(0, false)
                if type == "fail" then
                    self:playOpenFailAmi()
                    self:refreshRender(param, render)
                else
                    timeline:setLastFrameCallFunc(function()
                        self:playOpenSuccessAmi(param)
                        self:refreshRender(param, render)
                    end)
                end                
            end
        end
    end
end

function ClassRef:playOpenFailAmi(param, render)
	local aniNode = self._aniFailParticle
	if not aniNode then
		aniNode = cc.CSLoader:createNode(Res.EquipStrengthParticle, true)
        aniNode:findChild("Panel/name"):setString(L("AmazingBoxFilpFailed"))
        local size = self._ui.Panel:getContentSize()
        aniNode:setPosition(size.width/2, size.height/2)
        display.setAutoScale(aniNode)
        ccui.Helper:doLayout(aniNode)
		self:addChild(aniNode)
		self._aniFailParticle = aniNode
	end

	local timeline = aniNode:getTimeline()
	local aniParticle = aniNode:findChild("Panel/Particle")
	timeline:gotoFrameAndPlay(0, false)
    aniParticle:resetSystem()
end

function ClassRef:playOpenSuccessAmi(param)
    -- 需要复用十连抽奖励界面，故将数据拼成LotteryVo
    local drops = UD:parseDropIDToBagItem(param.dropID)
    local dataList = {}
    for k, v in ipairs(drops) do
        table.insert(dataList, {dropItemData = v})
    end
    app:sendMsg("MallController", "openLotteryResultView", dataList, "amazingBox", self._model:parseMoneyInfo())
end

function ClassRef:refreshRender(param, render)
    -- 刷新开宝箱之后的数据
    if render then
        render:setData(param)
    end
    self:updateMoney()
end

return ClassRef

